//
// Created by 陈坚 on 2023/3/24.
//

#ifndef KVSTORESIMPLE_PROTOBUF_H
#define KVSTORESIMPLE_PROTOBUF_H

#include <malloc.h>
#include <string>
#include <unordered_map>
#include<iostream>

class ProtoBuf{
public:
    ProtoBuf(int32_t size);
    ProtoBuf(int8_t *buf,int32_t size,bool isCopy = false);
    ~ProtoBuf();

    //编码的int值，表示长度，计算占用的存储字节数
    static int32_t computeInt32Size(int32_t value);
    //计算key，value占用的储存的字节数
    static int32_t computeItemSize(std::string key,ProtoBuf* value);
    //计算整个hashmap占用的储存的字节数
    static int32_t computeMapSize(std::unordered_map<std::string,ProtoBuf*> map);

    //不同value类型的存储字节数
    static int32_t computeValueInt32Size(){ return 4; }
    static int32_t computeValueDouble64Size(){ return 8; }
    static int32_t computeValueBooleanSize(){ return 1; }
public:
    //key
    std::string readString();
    //value
    ProtoBuf* readData();
    //int不拼接长度，读取编码的int值，表示长度
    int32_t  readInt();

public:
    //不同类型的value读取
    int32_t readValueInt();
    const char* readValueString();
    double_t readValueDouble();
    bool readValueBoolean();
    void* readValue();

public:
    bool isAtEnd(){
        return m_position == m_size;
    }

    int32_t length() const { return m_size; }

    //空闲内存
    int32_t spaceLeft() {
        return m_size - m_position;
    }

    int8_t *getBuf(){ return m_buf; }

    void restore(){
        m_position = 0;
    }

public:
    //raw的表示不拼接长度，写入编码的int值，表示长度
    void writeRawInt(int32_t value);
    //key
    void writeString(std::string value);
    //value
    void writeData(ProtoBuf* data);

public:
    //不同类型的value写入
    void writeValueInt(int32_t value);
    void writeValueString(const std::string& value);
    void writeValueDouble(double_t value);
    void writeValueBoolean(bool value);
    void writeValue(const void* value);

private:
    int8_t readByte();

    void writeByte(int8_t value);
private:
    int8_t *m_buf;
    int32_t  m_size;
    int32_t m_position;
    bool m_isCopy;
};

#endif //KVSTORESIMPLE_PROTOBUF_H
